<template>
  <div class="movie">
    <nav>
      <ul class="movie-nav">
        <li @click="handleCityPick">
          {{cityName}}
          <i class="yo-ico">&#xe623</i>
        </li>
        <li>
          <dl class="movie-nav-tab">
            <router-link 
              to="/home/movies/intheaters"
              v-slot="{navigate, isActive}"
              custom
            >
              <dt :class="{active: isActive}">
                <span @click="navigate">
                  热映
                </span>
              </dt>
            </router-link>
            <router-link 
              to="/home/movies/comingsoon"
              v-slot="{navigate, isActive}"
              custom
            >
              <dt :class="{active: isActive}">
                <span @click="navigate">
                  待映
                </span>
              </dt>
            </router-link>
          </dl>
        </li>
        <li>
          <i class="yo-ico">&#xe656;</i>
        </li>
      </ul>
    </nav>
    <div class="movie-list">
      <van-pull-refresh 
        v-model="refreshing" 
        @refresh="onRefresh"
      >
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <router-view :list="list"></router-view>
        </van-list>
      </van-pull-refresh>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { List, PullRefresh } from 'vant'
import { mapActions, mapState } from 'vuex'

Vue.use(List)
Vue.use(PullRefresh)

export default {
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      refreshing: false
    }
  },

  created() {
    this._initState()
  },

  computed: {
    ...mapState(['cityName', 'cityId'])
  },

  methods: {

    _initState() {
      // 分页的初始化
      this.limit = 10 // 每页多少条
      this.offset = 0 // 起始index
      this.cn = this.cityName // 城市
      this.ci = this.cityId
      this.hasMore = true // 是否到底了

      this.movieIds = []

      this.list = [],
      this.loading = false,
      this.finished = false,
      this.refreshing = false
    },

    // 请求数据
    async _loadIntheaterData() {
      let result = await this.$http.get({
        url: '/mmdb/movie/v2/list/hot.json',
        params: {
          limit: this.limit,
          offset: this.offset,
          ct: this.cn
        }
      })

      // 更新数据列表
      let hot = result.data.hot
      this.list = [ // 利用展开运算符来合并数组
        ...this.list,
        ...hot
      ]

      // 更新是否还有更多
      this.hasMore = result.data.paging.hasMore

      // 给this.offset添加10个位移
      this.offset += this.limit
    },

    async _loadComingsoonData() {
      if (this.offset === 0) {
        let result = await this.$http.get({
          url: '/ajax/comingList',
          params: {
            limit: this.limit,
            ct: this.ci,
            token: ''
          }
        })

        // 更新数据列表
        let coming = result.coming
        this.list = [ // 利用展开运算符来合并数组
          ...this.list,
          ...coming
        ]

        this.movieIds = result.movieIds

        // 下一页
        this.offset++

      } else {
        // console.log(this.movieIds.length, this.list.length)
        if (this.movieIds.length > this.list.length) {
          let start = this.offset * this.limit
          let result = await this.$http.get({
            url: '/ajax/moreComingList',
            params: {
              limit: this.limit,
              ct: this.ct,
              token: '',
              movieIds: this.movieIds.slice(start, start + this.limit).join(',')
            }
          })

          // 更新数据列表
          let coming = result.coming
          this.list = [ // 利用展开运算符来合并数组
            ...this.list,
            ...coming
          ]

          this.offset++

        } else {
          this.hasMore = false
        }
      }
    },

    async onLoad() {
      // refreshing 在用户下拉的时候就自动变为true
      if (this.refreshing) {
        // 偏移量的复位， 让列表从第一页加载
        this.offset = 0

        // 数据清空
        this.list = []

        // 下拉动作复位
        this.refreshing = false
      }

      // list组件会在第一次渲染的时候做一次数据加载
      const { name } = this.$route
      
      if (name === 'intheaters') {
        await this._loadIntheaterData()
      } else {
        await this._loadComingsoonData()
      }

      // 不显示loading图表
      this.loading = false

      // 没有更多了
      if (!this.hasMore) {
        this.finished = true
      }
    },

    onRefresh() {
      // 清空列表数据
      this.finished = false

      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      this.loading = true
      this.onLoad()
    },
  
    handleCityPick() {
      this.$router.push('/citypicker')
    }
  },

  watch: {
    $route() {
      this._initState()
      this.onLoad()
    }
  }
}
</script>

<style lang='stylus' scoped>
@import '../../../assets/stylus/border.styl'
.movie
  height 100%
  overflow hidden
  display flex
  flex-direction column
  nav
    height .44rem
    .movie-nav
      border_1px(0 0 1px 0)
      display flex

      li:first-child
        color #666
        flex 100
        padding-left .1rem
        line-height .44rem
        i
          font-size .2rem
          margin-left -0.08rem
          color #999

      li:nth-child(2)
        flex 231
        .movie-nav-tab
          height 100%
          display flex
          dt
            flex 1
            display flex
            font-size .16rem
            color #666
            align-items center
            justify-content flex-start
            span
              display inline-block
              line-height .44rem
              border-bottom solid .02rem #fff
            &.active
              color #cd4e44
              span
                border-bottom solid .02rem #cd4e44

      li:last-child
        flex 44
        line-height .44rem
        text-align center
        border_1px(0 0 0 1px)
        font-size .2rem
        color #cd4e44

  .movie-list
    flex 1
    overflow-y scroll
</style>